<template>
  <div :style="{display:block?'none':'block'}">
    
    <el-row style="display: flex;align-items: center;gap: 10px;">
      <div>选择课程</div>
      <el-select 
        v-model="curCourse"
        @change="changeCourse" 
        placeholder="请选择课程">
        <el-option
          v-for="item in courseOption"
          :key="item.id"
          :label="item.courseName"
          :value="item.id">
        </el-option>
      </el-select>  
    </el-row>
    
    <el-row style="margin: 10px;font-size: 20px;">查看学习单元</el-row>
    <el-divider></el-divider>
    
    <el-row type="flex" class="content">
      <el-col :span="8" class="tree-col">
        <el-row style="margin: 20px 10px;">
          <el-button type="primary" @click="handelAddChapter">添加章</el-button>
        </el-row>
        <el-row>
          <el-tree
            :data="treeData"
            :props="props"
            show-checkbox
            node-key="id"
            ref="tree"
            default-expand-all
            :current-node-key="13"
            style="width: 500px;"
            @node-click="handleNodeClick"
            :expand-on-click-node="false">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  v-if="!Object.keys(data).find(e=>e=='docPath')"
                  @click="() => appendSection(data)">
                  添加
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => handleEditUnit(node, data)">
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => handleDelUnit(node, data)">
                  删除
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  v-if="data.status == 1"
                  @click="() => handleCloseUnit(node, data)">
                  关闭
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  v-if="data.status == 0"
                  @click="() => handleOpenUnit(node, data)">
                  发布
                </el-button>
              </span>
            </span>
          </el-tree>
        </el-row>
      </el-col>
      <el-col :span="16" class="node-content" v-if="Object.keys(cur).length">
        <div class="line line1">
          <div class="title1">单元标题:</div>
          <div class="title1">{{ cur.unitTitle }}</div>
        </div>
        <div class="line">
          <div class="title1">简介:</div>
          <div class="title1">{{ cur.unitIntroduce }}</div>
        </div>
        <el-row class="file-area" v-if="Object.keys(cur).find(e=>e=='docPath')">
          <el-row class="video-area">
            <div style="margin-bottom: 30px;">视频资料：</div>
            <el-row v-if="cur.videoPath">
              <el-row type="flex" style="margin-bottom: 20px;">
                <el-button @click="downlaod({path:cur.videoPath})">下载视频</el-button>
                <el-button :style="{display:videoRenew?'none':'block'}" @click="videoRenew = true">重新上传</el-button>
              </el-row>
              <el-row :style="{display:videoRenew?'block':'none'}">
                <el-upload
                class="upload-demo"
                action="/common/upload"
                :auto-upload="false"
                :on-change="handleChange"
                :show-file-list="true"
              >
                <el-button slot="trigger" style="margin-right: 20px;">选取文件</el-button>
                <el-button type="primary" @click="submitUploadVideo">上传</el-button>
                <div slot="tip" style="margin-top: 10px;">只能上传mp4文件</div>
              </el-upload>
              </el-row>
            </el-row>
            <el-row v-else>
              <el-upload
                class="upload-demo"
                action="/common/upload"
                :auto-upload="false"
                :on-change="handleChange"
                :show-file-list="true"
              >
                <el-button slot="trigger" style="margin-right: 20px;">选取文件</el-button>
                <el-button type="primary" @click="submitUploadVideo">上传</el-button>
                <div slot="tip" style="margin-top: 10px;">只能上传mp4文件</div>
              </el-upload>
            </el-row>
          </el-row>
          <el-divider></el-divider>
          <el-row class="doc-area">
            <div style="margin-bottom: 30px;">文档资料：</div>
            <el-row v-if="cur.docPath">
              <el-row type="flex" style="margin-bottom: 20px;">
                <el-button @click="downlaod({path:cur.docPath})">下载文档</el-button>
                <el-button :style="{display:docRenew?'none':'block'}" @click="docRenew = true">重新上传</el-button>
              </el-row>
              <el-row :style="{display:docRenew?'block':'none'}">
                <el-upload
                class="upload-demo"
                action="/common/upload"
                :auto-upload="false"
                :on-change="handleChange"
                :show-file-list="true"
              >
                <el-button slot="trigger" style="margin-right: 20px;">选取文件</el-button>
                <el-button type="primary" @click="submitUploadDoc">上传</el-button>
                <div slot="tip" style="margin-top: 10px;">只能上传mp4文件</div>
              </el-upload>
              </el-row>
            </el-row>
            <el-row v-else>
              <el-upload
                class="upload-demo"
                action="/common/upload"
                :auto-upload="false"
                :on-change="handleChange"
                :show-file-list="true"
              >
                <el-button slot="trigger" style="margin-right: 20px;">选取文件</el-button>
                <el-button type="primary" @click="submitUploadDoc">上传</el-button>
                <div slot="tip" style="margin-top: 10px;">只能上传xxx文件</div>
              </el-upload>
            </el-row>
          </el-row>
        </el-row>
      </el-col>

    </el-row>
    
    
    <!-- 添加章节弹窗 -->
    <el-dialog :visible.sync="addDialogVisible" width="400px" title="添加学习单元" @closed="cancelDialog">
      <el-form :model="unitForm" label-position="left" label-width="80px">
          <el-form-item label="单元标题" prop="unitTitle">
              <el-input v-model="unitForm.unitTitle"></el-input>
          </el-form-item>
          <el-form-item label="单元简介" prop="unitIntroduce">
              <el-input v-model="unitForm.unitIntroduce"></el-input>
          </el-form-item>
          <el-form-item>
              <el-button @click="cancelDialog">取消</el-button>
              <el-button type="primary" @click="confirmSubmitAdd(unitForm)">确定</el-button>
          </el-form-item>
      </el-form>
    </el-dialog>
    
    
    <!-- 编辑章节弹窗 -->
    <el-dialog :visible.sync="editDialogVisible" width="400px" title="编辑学习单元" @closed="cancelDialog">
      <el-form :model="unitForm" label-position="left" label-width="80px">
          <el-form-item label="单元标题" prop="unitTitle">
              <el-input v-model="unitForm.unitTitle"></el-input>
          </el-form-item>
          <el-form-item label="单元简介" prop="unitIntroduce">
              <el-input v-model="unitForm.unitIntroduce"></el-input>
          </el-form-item>
          <el-form-item>
              <el-button @click="cancelDialog">取消</el-button>
              <el-button type="primary" @click="confirmSubmitEdit(unitForm)">确定</el-button>
          </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listClass } from '@/api/class';
import { addChapter, addSection, changeClass, closeUnit, docFileChange, downloadFile, editUnit, listUnit, openUnit, optionCourse, removeUnit, updateCourseFlie, videoFileChange } from '@/api/course';
import { getTeacherId } from '@/api/teacher';
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

export default {
  data(){
    return{
      block:false,
      file:undefined,
      teacherId:undefined,
      addDialogVisible: false,
      editDialogVisible: false,
      videoRenew: false,
      docRenew: false,
      courseQueryForm:{},
      courseOption:[],
      tableData:[],
      queryForm:{
        pageNum:1,
        pageSize:5
      },
      cur:{},
      upload:{},
      unitForm:{},
      treeData:[],
      props:{
        label:'unitTitle',
        children:'sectionListVos'
      },
      curCourse:undefined
    }
  },
  methods:{
    init(){
      let id = this.$store.state.user.id || JSON.parse(localStorage.getItem('user')).id
      
      getTeacherId(id).then(res=>{
          this.teacherId = res.data
          this.queryForm.teacherId = res.data
          listClass(this.queryForm).then(res=>{
            this.tableData = res.row
            if(!this.tableData.length){
                this.block = true
                MessageBox.alert(`当前教师账号未分配教学班，请联系活动管理员`).then(()=>{}).catch(()=>{})
            }else{
              this.getCourseOption({ teacherId:this.teacherId})
            }
          }).catch(()=>{})
      }).catch(()=>{})
    },
    getCourseOption(data){
      optionCourse(data).then(res=>{
        this.courseOption = res.data
        this.curCourse = this.courseOption[0].id
        listUnit(this.curCourse).then(res=>{
          this.treeData = res.data
        }).catch(()=>{})
      }).catch(()=>{})
    },
    changeCourse(id){
      console.log(id);
      this.curCourse = id
      listUnit(id).then(res=>{
        console.log('unit:',res);
        this.treeData = res.data
      }).catch(()=>{})
    },
    appendSection(data){
      this.addDialogVisible = true
      this.unitForm.fatherId = data.id
    },
    handleEditUnit(data){
      this.editDialogVisible = true
      this.unitForm = JSON.parse(JSON.stringify(data.data))
    },
    handelAddChapter(){
      this.addDialogVisible = true
    },
    handleDelUnit({data}){
      MessageBox.alert(`确定要删除学习单元<${data.unitTitle}>吗?`).then(()=>{
        removeUnit(data.id).then(res=>{
          Message.success(res.msg)
          listUnit(this.curCourse).then(res1=>{
            this.treeData = res1.data
          }).catch(()=>{})
        }).catch(()=>{})
      }).catch(()=>{})
    },
    handleCloseUnit({data}){
      MessageBox.alert(`确定要关闭学习单元<${data.unitTitle}>吗?`).then(()=>{
        closeUnit(data.id).then(res=>{
          Message.success(res.msg)
          listUnit(this.curCourse).then(res1=>{
            this.treeData = res1.data
          }).catch(()=>{})
        }).catch(()=>{})
      }).catch(()=>{})
    },
    handleOpenUnit({data}){
      MessageBox.alert(`确定要发布学习单元<${data.unitTitle}>吗?`).then(()=>{
        openUnit(data.id).then(res=>{
          Message.success(res.msg)
          listUnit(this.curCourse).then(res1=>{
            this.treeData = res1.data
          }).catch(()=>{})
        }).catch(()=>{})
      }).catch(()=>{})
      
    },
    cancelDialog(){
      this.editDialogVisible = false
      this.addDialogVisible = false
      this.unitForm = {}
    },
    confirmSubmitAdd(data){
      data.courseId = this.curCourse
      data.learningScore = 0
      if(!data.fatherId){
        addChapter(data).then(res=>{
          Message.success(res.msg)
          listUnit(this.curCourse).then(res1=>{
            this.treeData = res1.data
          }).catch(()=>{})
        }).catch(()=>{})
      }else{
        addSection(data).then(res=>{
          Message.success(res.msg)
          listUnit(this.curCourse).then(res1=>{
            this.treeData = res1.data
          }).catch(()=>{})
        }).catch(()=>{})
      }
      this.addDialogVisible = false
      this.unitForm = {}
    },
    confirmSubmitEdit(data){
      editUnit(data).then(res=>{
        Message.success(res.msg)
        listUnit(this.curCourse).then(res1=>{
          this.treeData = res1.data
        }).catch(()=>{})
      }).catch(()=>{})
      this.editDialogVisible = false
    },
    handleNodeClick(data){
      this.cur = data
      console.log(this.$refs.tree.getCurrentKey());
      
      console.log(data);
      
    },
    handleChange(uploadedFile){
      console.log('uploadedFile',uploadedFile);
      
      this.file = uploadedFile.raw;
    },
    submitUploadDoc(){
      const formData = new FormData();
      formData.append('file', this.file);

      updateCourseFlie(formData).then(res=>{
        this.upload.docPath = res.data.split('\\').join('/')
        this.upload.id = this.cur.id
        docFileChange(this.upload).then(res=>{
          Message.success(res.msg)
          this.cur = {}
          listUnit(this.curCourse).then(res1=>{
            this.treeData = res1.data
          }).catch(()=>{})
        }).catch(()=>{})
      }).catch(err=>{})
    },
    submitUploadVideo(){
      const formData = new FormData();
      formData.append('file', this.file);

      updateCourseFlie(formData).then(res=>{
        this.upload.videoPath = res.data.split('\\').join('/')
        this.upload.id = this.cur.id
        videoFileChange(this.upload).then(res=>{
          Message.success(res.msg)
          this.cur = {}
          this.videoRenew = false
          listUnit(this.curCourse).then(res1=>{
            this.treeData = res1.data
          }).catch(()=>{})
        }).catch(()=>{})
      }).catch(err=>{})
    },

    // 下载文件
    downlaod(data){
      let list = data.path.split('/')
      
      let name = list[list.length-1]
      axios({
        method: 'POST',
        url: '/common/download',
        headers: {
          Authorization: this.$cookies.get('cp-token')
        },
        responseType: 'blob' // 关键设置，指定接收的响应类型为blob（二进制大对象），用于接收文件流
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers['content-type'] }));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', name); // 设置下载文件名，与后端设置的尽量一致
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }).catch((error) => {
        console.log(error);
      });
    },
  },
  created(){
    this.init()
  }
}
</script>

<style lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.content{
  height: 500px;
  .tree-col{
    border-right: 1px solid #cfcccc !important;
  }
}
.node-content{
  padding: 30px;
}
.line{
  display: flex;
  gap: 20px;
  font-size: 20px;
}
.line1{
  font-size: 30px;
  margin-bottom: 20px;
}
.file-area{
  margin-top: 40px;
}
</style>